package com.icesoft.base.manager.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.PropertiesPropertySourceLoader;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.IOException;

public class ManagerDefaultConfigPostProcessor implements EnvironmentPostProcessor {

	@Override
	public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
		Resource path = new ClassPathResource("config/default-config.properties");
		PropertySource<?> propertySource = load(path);
		System.out.println("加载默认配置：" + propertySource.getSource());
		environment.getPropertySources().addLast(propertySource);
	}

	private PropertySource<?> load(Resource path) {
		if (!path.exists()) {
			throw new IllegalArgumentException("Resource " + path + " does not exist");
		}
		PropertiesPropertySourceLoader loader = new PropertiesPropertySourceLoader();
		try {
			return loader.load("classpath:config/default-config.properties", path).get(0);
		} catch (IOException ex) {
			throw new IllegalStateException("Failed to load yaml configuration from " + path, ex);
		}
	}

}
